<?php

// 参考：http://www.php.net/manual/zh/pdo.connections.php
// https://segmentfault.com/a/1190000004106175

include_once 'db_config.php';
try {
// array(PDO::ATTR_PERSISTENT => true) 开启持久化连接
    $dbh = new PDO('mysql:host=localhost;dbname='.$db['db_name'], $db['user'], $db['pwd'], array(PDO::ATTR_PERSISTENT => true));
    //  页面编码的声明,否则遇到中文会出现乱码
    $dbh->query('set names utf8;');
    if (empty($_POST["date_start"]) & empty($_POST["date_end"])) {
        // 获取指定日期的净增用户总量
        $next_day = date("Y-m-d", strtotime('-7 days'));
        $end_day = date('Y-m-d', strtotime('-1 days'));
    } else {
        $next_day = $_POST['date_start'];
        $end_day = $_POST['date_end'];
    }
    $arr = array();
    $sql = 'SELECT ref_date,msgid,title,details FROM `articletotal` where ref_date>="' . $next_day . '" and ref_date<= "' . $end_day . '" order by msgid asc';

    foreach ($dbh->query($sql) as $row) {
            // 把日期和用户数单独组成列 | 变量追加到数组中
        $arr['date'][] = $row['ref_date'];
        $arr['title'][] = $row['title'];
        $arr['msgid'][] = $row['msgid'];
        $details_arr=json_decode($row['details'],true); // 把json数据转化为数组，将第二个参数为true时将转化为数组
        
        $details_key = count($details_arr) - 1;
        $arr['target_user'][] = $details_arr[$details_key]['target_user'];
        $arr['int_page_read_user'][] = $details_arr[$details_key]['int_page_read_user'];
        $arr['a'][] = round($details_arr[$details_key]['int_page_read_user']/$details_arr[$details_key]['target_user']*100,2);
        $arr['share_user'][] = $details_arr[$details_key]['share_user'];
        $arr['add_to_fav_user'][] = $details_arr[$details_key]['add_to_fav_user'];
        $arr['b'][] = round($details_arr[$details_key]['share_user']/$details_arr[$details_key]['target_user']*100,2);
    }
    // 把数据转换成json格式
    $data = json_encode($arr);
    echo $data;

    // 现在运行完成，在此关闭连接
    $dbh = null;
} catch (PDOException $e) {
    print "Error!: " . $e->getMessage() . "<br/>";
    die();
}
?>